﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CustomControls_Usuarios : System.Web.UI.UserControl
{

    protected int Id
    {
        get
        {
            if (ViewState["id"] == null) return 0;
            return (int)ViewState["id"];
        }
        set { ViewState["id"] = value; }
    }
    protected String[] Message
    {
        get
        {
            if (Session["Message"] == null)
            {
                String[] m = {"",""};
                return m;
            }
            return (String[])Session["Message"];
        }
        set { Session["Message"] = value; }
    }
    private bool Add
    {
        get
        {
            if (ViewState["add"] != null)
            {
                return (bool)ViewState["add"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["add"] = value;
        }
    }
    private bool Edit
    {
        get
        {
            if (ViewState["Edit"] != null)
            {
                return (bool)ViewState["Edit"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["Edit"] = value;
        }
    }
    private bool View
    {
        get
        {
            if (ViewState["View"] != null)
            {
                return (bool)ViewState["View"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["View"] = value;
        }
    }
    private bool Disable
    {
        get
        {
            if (ViewState["Disable"] != null)
            {
                return (bool)ViewState["Disable"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["Disable"] = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            
            FillRoles();
            String[] msg = { "", "" };
            Message = msg;
            if (!String.IsNullOrEmpty(Request.QueryString["id"]) && Request.Url.ToString().Contains("Editar.aspx"))
            {
                int cid = 0;
                int.TryParse(Request.QueryString["id"], out cid);
                this.Id = cid;
                BLLUser bll = new BLLUser();
                User u = bll.GetUserById(this.Id);
                
                if (u.Id > 0)
                {
                    populateInfo(u);
                    HidePasswordPanel();
                }
                else
                {
                    String[] error = { Resources.Resource.ERROR, Resources.Resource.USER_NOT_FOUND };
                    Message = error;
                    this.Response.Redirect("Default.aspx?recover=y");
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    String[] error = { Resources.Resource.ERROR, Resources.Resource.INVALID_URL };
                    Message = error;
                    this.Response.Redirect("Default.aspx?recover=y");
                }
            }
            SetupPageByUserRoles();
        }
        ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "0";
    }
    private void HidePasswordPanel() 
    {
        pnlPassword.Attributes.Add("style", "display:none");
        lnkChangePassword.Attributes.Add("style", "display:block");
        Cvalidator.Enabled = false;
        CCvalidator.Enabled = false;
        cmpPassword.Enabled = false;
        hdnChangePassword.Value = "0";
        lblPassword.Text = "<span class='required-mark'>*</span> Contrase&ntilde;a:";
        lblConfPassword.Text = "<span class='required-mark'>*</span> Confirme Contrase&ntilde;a:";

    }
    private void populateInfo(User u)
    {
        txtName.Text = u.FirstName;
        txtLastName.Text = u.LastName;
        txtEmail.Text = u.Email;
        txtUsername.Text = u.Username;
        chkEnabled.Checked = u.IsEnabled;
        drpRole.SelectedValue = u.RoleId.ToString();
    }
    private void FillRoles()
    {
        BLLUser bll = new BLLUser();
        List<Role> roles = new List<Role>();
        roles = bll.GetEnabledUserRoles();
        drpRole.Items.Clear();
        foreach(Role r in roles)
        {
            drpRole.Items.Add(new ListItem(r.Name,r.Id.ToString()));
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        User u = new User();
        bool changePass = false;
        u.FirstName = txtName.Text;
        u.LastName = txtLastName.Text;
        u.Email = txtEmail.Text;
        u.RoleId = Convert.ToInt64(drpRole.SelectedValue);
        u.Username = txtUsername.Text;
        u.Password = this.txtPassword.Text.Trim();
          
        u.IsEnabled = chkEnabled.Checked;
        if (this.Id == 0)
        {
            u.CreatedBy = Util.GetCurrentUserId();
            u.CreatedDate = DateTime.Now;
        }
        else
        {
            if (hdnChangePassword.Value == "1")
            {
                changePass = true;
            }
            u.Id = this.Id;
        }

        BLLUser bll = new BLLUser();
        if (bll.Save(u,changePass))
        {
            String[] error = { Resources.Resource.SUCCESS, Resources.Resource.USER_SAVED };
            Message = error;
            this.Response.Redirect("Default.aspx?recover=y");
        }
        else
        {

            ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "1";
            ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.UPDATE_ERROR;
            ((Literal)Page.Master.FindControl("ltrMessageType")).Text = Resources.Resource.ERROR;

        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        this.Response.Redirect("Default.aspx?recover=y");
    }
    protected void SetupPageByUserRoles()
    {
        List<SessionPermissions> userPermissions = new List<SessionPermissions>();
        userPermissions = (List<SessionPermissions>)Session[GlobalNames.UserPermissions];
        userPermissions = (from upb in userPermissions
                           where upb.ModuleId == (long)GlobalEnums.Modules.Usuarios
                           select upb).ToList();
        if (userPermissions.Count() > 0)
        {
            foreach (SessionPermissions up in userPermissions)
            {
                if (up.PermissionId == (long)GlobalEnums.Permissions.Agregar)
                    Add = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Editar)
                    Edit = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Ver)
                    this.View = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Habilitar_Deshabilitar)
                    this.Disable = true;
            }
            if (!View)
                this.Response.Redirect("~/Default.aspx");
            if (!Add && Id == 0)
            {
                this.Response.Redirect("Default.aspx");
            }
            if (Id > 0 && !Edit)
                btnSave.Visible = false;
            if (!Disable)
                chkEnabled.Enabled = false;
        }
        else
        {
            this.Response.Redirect("~/Default.aspx");
        }
    }
}